#import "DDCouponViewController.h"
#import "DDCouponSeg.h"
#import "DDCouponCell.h"
#import "DDCouponsModel.h"
@interface DDCouponViewController ()<UICollectionViewDelegate, UICollectionViewDataSource,UIScrollViewDelegate>
@property (nonatomic, strong) DDCouponSeg *seg;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionView *unusableCollView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UICollectionViewFlowLayout *unusableLayout;
@property (nonatomic, strong) DDButton *useBtn;
@property (nonatomic, assign) CGSize size;
@end
@implementation DDCouponViewController
- (void)viewDidLoad {
    [super viewDidLoad];
}
- (DDCouponSeg *)seg
{
    if (!_seg)
    {
        _seg = [[DDCouponSeg alloc] initWithSize:self.size];
        [self.ddview addSubview:_seg];
        _seg.c_top.equal(self.ddview.bar.c_bottom);
        _seg.c_left.equal(self.ddview).with.coffset(GAP);
        _seg.c_right.equal(self.ddview).with.coffset(-GAP);
        _seg.c_height.equal(JTWCOUPONSEGHEIGHT);
    }
    return _seg;
}
- (UIScrollView *)scrollView
{
    if (!_scrollView)
    {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.bounces  = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        _scrollView.showsHorizontalScrollIndicator = NO;
        [self.ddview addSubview:_scrollView];
        _scrollView.c_top.equal(self.seg.c_bottom);
        _scrollView.c_left.equal(self.ddview);
        _scrollView.c_right.equal(self.ddview);
        _scrollView.c_bottom.equal(self.ddview).with.coffset(-GAP);
    }
    return _scrollView;
}
- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
        [_collectionView registerClass:[DDCouponCell class] forCellWithReuseIdentifier:@"DDCouponCell"];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [self.scrollView addSubview:_collectionView];
        _collectionView.c_top.equal(self.scrollView);
        _collectionView.c_left.equal(self.scrollView).with.coffset(GAP);
        if (self.showUseBtn)
            _collectionView.c_bottom.equal(self.useBtn.c_top).with.coffset(-GAP);
        else
            _collectionView.c_bottom.equal(self.ddview).with.coffset(-GAP);
    }
    return _collectionView;
}
- (UICollectionView *)unusableCollView
{
    if (!_unusableCollView)
    {
        _unusableCollView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.unusableLayout];
        [_unusableCollView registerClass:[DDCouponCell class] forCellWithReuseIdentifier:@"JTWCouponCellUnuse"];
        _unusableCollView.backgroundColor = [UIColor clearColor];
        _unusableCollView.delegate = self;
        _unusableCollView.dataSource = self;
        [self.scrollView addSubview:_unusableCollView];
        _unusableCollView.c_top.equal(self.scrollView);
        _unusableCollView.c_left.equal(self.scrollView).with.coffset(self.size.width + GAP);
        _unusableCollView.c_bottom.equal(self.ddview).with.coffset(-GAP);
    }
    return _unusableCollView;
}
- (UICollectionViewFlowLayout *)layout
{
    if (!_layout)
    {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.minimumLineSpacing = GAP;
        _layout.minimumInteritemSpacing = 0;
        _layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    }
    return _layout;
}
- (UICollectionViewFlowLayout *)unusableLayout
{
    if (!_unusableLayout)
    {
        _unusableLayout = [[UICollectionViewFlowLayout alloc] init];
        _unusableLayout.minimumLineSpacing = GAP;
        _unusableLayout.minimumInteritemSpacing = 0;
        _unusableLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    }
    return _unusableLayout;
}
- (DDButton *)useBtn
{
    if (!_useBtn)
    {
        _useBtn = [[DDButton alloc] init];
        _useBtn.title = @"立即使用";
        _useBtn.backgroundColor = TEXT_GRAY_COLOR;
        _useBtn.layer.cornerRadius = GAP / 2.0;
        _useBtn.hidden = !self.showUseBtn;
        _useBtn.userInteractionEnabled = NO;
        [_useBtn addTarget:self action:@selector(yjd_actionForUseBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.ddview addSubview:_useBtn];
        _useBtn.c_bottom.equal(self.ddview).with.coffset(-GAP);
        _useBtn.c_left.equal(self.ddview).with.coffset(GAP);
        _useBtn.c_right.equal(self.ddview).with.coffset(-GAP);
        _useBtn.c_height.equal(BUTTONHEIGHT);
    }
    return _useBtn;
}
- (CGSize)size
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        CGRect bounds = [[[[UIViewController currentVC] presentingViewController] view] bounds];
        return bounds.size;
    }
    else
    {
        UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
        if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
            return CGSizeMake(SCREEN_MIN_LENGTH - GAP * 2, SCREEN_MIN_LENGTH);
        else
            return CGSizeMake(SCREEN_MIN_LENGTH, SCREEN_MIN_LENGTH - GAP * 2);
    }
}
- (CGSize)yjd_cellItemSize:(UIInterfaceOrientation)orientation
{
    self.scrollView.contentSize = CGSizeMake(self.size.width * 2, self.size.height - JTWNaviBarHeight - BUTTONHEIGHT - GAP * 3 - JTWCOUPONSEGHEIGHT);
    
    self.collectionView.c_width.equal(self.size.width - GAP *2.0);
    
    self.unusableCollView.c_width.equal(self.size.width - GAP * 2.0);
    self.unusableCollView.c_left.equal(self.scrollView).with.coffset(self.size.width + GAP);
    CGFloat width = 0;
    if (self.size.width + GAP * 2 == SCREEN_WIDTH)
    {
        width = (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight)?((self.size.width - GAP * 3) / 2.0):(self.size.width - GAP * 2);
    }
    else
    {
        width = (self.size.width - GAP * 2);
    }
    return CGSizeMake(width , JTWCOUPONCELLHEIGHT);
}
- (void)yjd_screenRotate:(UIInterfaceOrientation)orientation
{
    [super yjd_screenRotate:orientation];
    [self.seg yjd_segRoll];
    CGSize itemsize = [self yjd_cellItemSize:orientation];
    self.layout.itemSize = itemsize;
    self.unusableLayout.itemSize = itemsize;
    [self.scrollView setContentOffset:CGPointMake(self.size.width * self.seg.currentIndex, 0) animated:YES];
}
- (void)yjd_actionForUseBtn
{
    if (self.showUseBtn)
    {
        NSInteger index = ([self.useBtn.title isEqualToString:@"立即使用"])?self.selectIndex:self.coupons.count + 100;
        [self.presentingViewController setValue:[NSString stringWithFormat:@"%ld",index] forKey:@"youhuiIndex"];
    }
    [self dismissViewControllerAnimated:YES completion:^{
        DDViewController * vc = (DDViewController *)self.presentingViewController;
        [vc reload];
    }];
}
#pragma mark CollectionViewDelegate & DataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return ([collectionView isEqual:self.collectionView])?self.coupons.count:self.discoupons.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DDCouponCell *cell = nil;
    if ([collectionView isEqual:self.collectionView])
    {
        if (indexPath.row > 1)
        {
            [collectionView registerClass:[DDCouponCell class] forCellWithReuseIdentifier:[NSString stringWithFormat:@"DDCouponCell%ld",indexPath.row - 1]];
        }
        NSString *cellID = (indexPath.row == 0)?@"DDCouponCell":[NSString stringWithFormat:@"DDCouponCell%ld",indexPath.row];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
        cell.selected = (indexPath.row == self.selectIndex)?YES:NO;
        [collectionView registerClass:[DDCouponCell class] forCellWithReuseIdentifier:[NSString stringWithFormat:@"DDCouponCell%ld",indexPath.row + 1]];
    }
    else
    {
        NSString *cellID = (indexPath.row == 0)?@"JTWCouponCellUnuse":[NSString stringWithFormat:@"JTWCouponCellUnuse%ld",indexPath.row];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
        [collectionView registerClass:[DDCouponCell class] forCellWithReuseIdentifier:[NSString stringWithFormat:@"JTWCouponCellUnuse%ld",indexPath.row + 1]];
    }
    DDCouponsModelPara para;
    if ([collectionView isEqual:self.collectionView])
        [self.coupons[indexPath.row] getBytes:&para length:sizeof(para)];
    else
        [self.discoupons[indexPath.row] getBytes:&para length:sizeof(para)];
    cell.userInteractionEnabled = ([collectionView isEqual:self.collectionView])?YES:NO;
    
    DDCouponCellPara couponCellPara;

    couponCellPara.title = ([para.gameid intValue] == 0)?@"平台所有游戏通用":para.gamename;
    couponCellPara.date = ([para.expirydate length] == 0)?@"永久":para.expirydate;
    couponCellPara.tips =  ([para.limit floatValue] == 0)?@"不限金额":[NSString stringWithFormat:@"满足%f元可用",[para.limit floatValue]];
    couponCellPara.money = para.value;
    couponCellManager().setPara(cell, couponCellPara);
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DDCouponCell *cell = (DDCouponCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.selectIndex inSection:0]];
    cell.selected = NO;
    self.selectIndex = indexPath.row;
    if (self.showUseBtn)
    {
        NSInteger index = [[self.presentingViewController valueForKey:@"youhuiIndex"] integerValue];
        self.useBtn.backgroundColor = helpermanger().getPara().color;
        self.useBtn.userInteractionEnabled = YES;
        self.useBtn.title = (index == indexPath.row)?@"取消使用":@"立即使用";
    }
}
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:self.scrollView])
    {
        if (scrollView.contentOffset.x == 0)
        {
            self.seg.currentIndex = 0;
        }
        else if (scrollView.contentOffset.x == self.size.width)
        {
            self.seg.currentIndex = 1;
        }
        self.useBtn.backgroundColor = (self.seg.currentIndex == 0)?helpermanger().getPara().color:TEXT_GRAY_COLOR;
        self.useBtn.hidden = (self.showUseBtn)?((self.seg.currentIndex == 0)?NO:YES):YES;
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.ddview.bar.title = @"优惠中心";
    WS(self);
    self.seg.currentIndex = 0;
    self.scrollView.hidden = NO;
    self.seg.block = ^{
        DeLog(@"当前选择%d",weakSelf.seg.currentIndex);
        [weakSelf.scrollView setContentOffset:CGPointMake(self.size.width * weakSelf.seg.currentIndex, 0) animated:YES];
    };
    CGSize itemSize = [self yjd_cellItemSize:[[UIApplication sharedApplication] statusBarOrientation]];
    self.layout.itemSize = itemSize;
    self.unusableLayout.itemSize = itemSize;
    if (self.selectIndex <= self.coupons.count)
    {
        self.useBtn.title = @"取消使用";
        self.useBtn.backgroundColor = helpermanger().getPara().color;
        self.useBtn.userInteractionEnabled = YES;
        if ([[UIApplication sharedApplication] statusBarOrientation] != UIDeviceOrientationLandscapeRight && [[UIApplication sharedApplication] statusBarOrientation] != UIDeviceOrientationLandscapeLeft)
        {
            [self.collectionView registerClass:[DDCouponCell class] forCellWithReuseIdentifier:[NSString stringWithFormat:@"DDCouponCell%ld",self.selectIndex - 1]];
            [self.collectionView layoutIfNeeded];
            
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.selectIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
